<?php

namespace addons\cloud_market\controller\api\developer;

use addons\cloud_market\controller\api\CloudMarketApiController;
use addons\cloud_market\model\CloudMarketAddon;
use addons\cloud_market\model\CloudMarketAddonVersions;
use addons\cloud_market\model\CloudMarketAttachment;
use addons\cloud_market\model\CloudMarketDeveloper;
use app\common\services\Attachment as AttachmentService;
use hiduoke\services\upload\driver\Cos;
use hiduoke\services\UploadService;
use think\file\UploadedFile;

class Cloud extends CloudMarketApiController
{
    protected $notApiLogin = ["*"];

    private $err = '';

    public function index()
    {
        $dev_id = input('dev_id', '');
        $token = input('token', '');
        $dev_user = (new CloudMarketDeveloper())->where(['token' => $token, 'id' => $dev_id])->find();
        if ($dev_user) {
            return $this->success('身份认证成功');
        } else {
           return $this->error('token错误');
        }
    }


    public function getFileUrl($url = '', $user_id = 0)
    {
        if (!$url)return $this->error('参数错误');
        stream_context_set_default([
            'ssl' => [
                'verify_peer'      => false,
                'verify_peer_name' => false,
            ],
        ]);
        // 获取图片名
        $mimeType = get_headers($url, true)['Content-Type'] ?? false;
        $originalName = basename($url) ?? false;
        if (!$mimeType || !$originalName) {
//           return $this->error('参数错误');
            $this->err = "参数错误";
            return  false;
        }
        try {
            $imageData = file_get_contents($url);
            $tempFilePath = tempnam(sys_get_temp_dir(), 'image');
            file_put_contents($tempFilePath, $imageData);
            $uploadedFile = new UploadedFile($tempFilePath, $originalName, $mimeType, 0);
//            $upload = new Cos();

            $path = (new AttachmentService())->getPathByType(0);
            $upload = UploadService::init();
            $res = $upload->path($path)->validate()->save($uploadedFile);

//            $res = $upload->path("/uploads/" . date("Ymd") . "")->validate()->save($uploadedFile);
        } catch (\Exception $e) {
//           return $this->error("上传应用包错误".$e->getMessage());
            $this->err = "上传应用包错误".$e->getMessage();
            return  false;
        }
        if ($res == false) {
//           return $this->error('上传应用包失败');
            $this->err = "上传应用包失败";
            return false;
        } else {
            $fileInfo = $upload->getUploadInfo();
            $data = array(
                'admin_id'    => 0,
                'user_id'     => $user_id,
                'filesize'    => $fileInfo['size'],
                'filename'    => $fileInfo['oldName'],
                'imagewidth'  => 0,
                'imageheight' => 0,
                'imagetype'   => 0,//
                'imageframes' => 0,
                'url'         => $fileInfo['url'],
                'uploadtime'  => time(),
                'storage'     => 'cos',
            );
            (new CloudMarketAttachment())->save($data);
            return $data;
        }
    }

    /**
     * 更新版本
     */
    public function updateVersion()
    {
        $addon_name = input('addon_name', ''); // 应用ID
        $version = input('version', ''); // 版本号
        $down_url = input('down_url', ''); // 下载地址
        $name = input('name', ''); // 版本名称
        $content = htmlspecialchars_decode(input('content', '', 'htmlspecialchars')); // 更新内容
        $dev_id = input('dev_id', '');
        $token = input('token', '');
        if (!$version || !$name || !$content || !$token || !$addon_name) {
           return $this->error("参数不全");
        }
        $dev_user = (new CloudMarketDeveloper())->where(['token' => $token, 'id' => $dev_id])->find();
        if (!$dev_user) {
           return $this->error('token错误，请检查配置',input());
        }
        // 获取应用
        $addon = (new CloudMarketAddon())->where(['name' => $addon_name, 'dev_id' => $dev_user['id']])->find();
        if (!$addon) {
           return $this->error('应用不存在,请先创建应用');
        }
        // 获取对应版本判断是更新还是新增
        $addon_version = (new CloudMarketAddonVersions())->where(['version' => $version, 'aid' => $addon['id']])->find();
        if ($down_url) {
            $file_data = $this->getFileUrl($down_url, $dev_user['user_id']);
            if(!$file_data){
                return $this->error($this->err);
            }
        }
        if (!$addon_version) {
            // 新增
            $data = array(
                'aid'         => $addon['id'],
                'version'     => $version,
                'name'        => $name,
                'content'     => $content,
                'show_switch' => 1
            );
            $down_file = $file_data['url'] ?? '';
            if ($down_file) {
                $data['down_file'] = $down_file;
            }
            (new CloudMarketAddonVersions())->save($data);
            return $this->success("新增版本成功");
        } else {
            //编辑
            if(isset($file_data['url']) && $file_data['url']){
                $addon_version->down_file = $file_data['url'] ?? '';
            }
            $addon_version->name = $name;
            $addon_version->content = $content;
            $addon_version->save();
            return $this->success("更新版本成功");
        }
    }
}
